<template>
  <md-nav-bar title="添加音乐" backgroundColor="#eaf8f4" />
  <view class="container">
    <!-- 表单内容 -->
    <view class="form">
      <uni-forms ref="form" :modelValue="data.formData" label-position="top" :rules="data.rules" label-width="100">
        <uni-forms-item label="歌名" name="name" required>
          <uni-easyinput type="text" v-model="data.formData.name" placeholder="请输入歌名" />
        </uni-forms-item>
<!--        <uni-forms-item label="作词" name="wording">-->
<!--          <uni-easyinput type="text" v-model="data.formData.wording" placeholder="请输入作词" />-->
<!--        </uni-forms-item>-->
<!--        <uni-forms-item label="作曲" name="composer">-->
<!--          <uni-easyinput type="text" v-model="data.formData.composer" placeholder="请输入作曲" />-->
<!--        </uni-forms-item>-->
<!--        <uni-forms-item label="演唱" name="singer">-->
<!--          <uni-easyinput type="text" v-model="data.formData.singer" placeholder="请输入演唱" />-->
<!--        </uni-forms-item>-->
<!--        <uni-forms-item label="创作背景" name="background">-->
<!--          <uni-easyinput-->
<!--            type="textarea"-->
<!--            :maxlength="2000"-->
<!--            autoHeight-->
<!--            v-model="data.formData.background"-->
<!--            placeholder="请输入创作背景" />-->
<!--        </uni-forms-item>-->
        <uni-forms-item label="音频" name="songUrl" required>
          <template v-slot:label>
            <view class="form-item-label">
              <text class="required-red">*</text>
              <text>音频</text>
              <text class="red-tip">先把音频文件上传到微信的“文件传输助手"上，点击导入</text>
            </view>
          </template>
          <uni-file-picker
            v-model="data.formData.songUrl"
            :sourceType="['album']"
            file-extname="mp3,wav"
            return-type="object"
            file-mediatype="all"
            @select="(e: any) => handleUpload(e, 'songUrl')">
            <view class="upload-box" v-if="Object.keys(data.formData?.songUrl || {})?.length == 0">
              <text class="plus">+</text>
            </view>
          </uni-file-picker>
        </uni-forms-item>
        <uni-forms-item label="歌词" name="lyric" required>
          <template v-slot:label>
            <view class="form-item-label">
              <text class="required-red">*</text>
              <text>歌词</text>
              <text class="red-tip">先把文本上传到微信的“文件传输助手”，复制粘贴在这里</text>
            </view>
          </template>
          <view class="form-item-textarea">
            <uni-easyinput
                type="textarea"
                :maxlength="1000"
                v-model="data.formData.lyric"
                placeholder="请输入歌词" />
          </view>
        </uni-forms-item>
<!--        <uni-forms-item label="曲谱图（可选）" name="musicScoreUrl">-->
<!--          <template v-slot:label>-->
<!--            <view class="form-item-label">-->
<!--              <text>曲谱图（可选）</text>-->
<!--              <text class="red-tip">曲谱图可使测评结果更精准</text>-->
<!--            </view>-->
<!--          </template>-->
<!--          <uni-file-picker-->
<!--            return-type="object"-->
<!--            file-mediatype="image"-->
<!--            :image-styles="{ height: '160rpx', width: '100%' }"-->
<!--            @select="(e: any) => handleUpload(e, 'musicScoreUrl')">-->
<!--            <view class="upload-box">-->
<!--              <text class="plus">+</text>-->
<!--            </view>-->
<!--          </uni-file-picker>-->
<!--        </uni-forms-item>-->
<!--        <uni-forms-item label="封面" name="coverUrl">-->
<!--          <uni-file-picker-->
<!--            return-type="object"-->
<!--            file-mediatype="image"-->
<!--            :image-styles="{ height: '160rpx', width: '100%' }"-->
<!--            @select="(e: any) => handleUpload(e, 'coverUrl')">-->
<!--            <view class="upload-box">-->
<!--              <text class="plus">+</text>-->
<!--            </view>-->
<!--          </uni-file-picker>-->
<!--        </uni-forms-item>-->
      </uni-forms>
      <!-- 免责声明 -->
      <view class="disclaimer">
        <checkbox :checked="checked" @click="checked = !checked" />
        <text>我已阅读并同意</text>
        <md-agreement text="免责声明" />
      </view>
      <!-- 提交按钮 -->
      <button class="submit-btn" @click="submit">提交</button>
      <view class="tip">消耗{{ data.adou }}个A豆</view>
      <view class="tip">预计耗时4到6分钟</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
// 接口
import api from '@/api/index';
import type { Music } from '@/api/data';
// 工具
import { Toast } from '@/utils/util';
import { uploadToQiniu } from '@/api/util';
import { onLoad, onShow } from '@dcloudio/uni-app';
enum fileEnum {
  songUrl = 0,
  musicScoreUrl = 1,
  coverUrl = 2,
}

const data = reactive({
  formData: {
    name: '',
    wording: '',
    composer: '',
    singer: '',
    background: '',
    lyric: '',
  } as Record<string, any>,
  rules: {
    name: {
      rules: [
        {
          required: true,
          errorMessage: '请输入歌名',
        },
      ],
    },
    lyric: {
      rules: [
        {
          required: true,
          errorMessage: '请输入歌词',
        },
      ],
    },
    songUrl: {
      rules: [
        {
          required: true,
          errorMessage: '请上传音频文件',
        },
      ],
    },
  },
  adou: 0,
});
const form = ref(null);

const checked = ref(false);

const handleUpload = async (e: any, key: keyof typeof fileEnum) => {
  uni.showLoading({ title: '上传中...', mask: true });
  let { tempFiles } = e;
  const file = tempFiles?.[0];
  // 音频文件只支持mp3和wav格式
  if (key === 'songUrl' && !['mp3', 'wav'].includes(file?.extname)) {
    uni.showModal({
      title: '提示',
      content: '音频文件只支持mp3和wav格式',
      showCancel: false,
    });
    data.formData[key] = {};
    uni.hideLoading();
    return;
  }
  try {
    const res: any = await uploadToQiniu(file, 'isong/music/' + key);
    if (res) {
      // 格式化组件需要的格式
      const value = {
        url: res.url,
        extname: res?.extname,
        name: res?.name,
      };
      data.formData[key] = value;
    } else {
      data.formData[key] = {};
    }
  } catch (e) {
    console.log('上传异常',e)
    data.formData[key] = {};
  }
  uni.hideLoading();
};

const submit = async () => {
  if (!checked.value) {
    Toast('请勾选《免责声明》');
    return;
  }
  try {
    const res = await form.value?.validate();
    const values = {
      ...res,
      // 处理提交格式
      coverUrl: res?.coverUrl?.url,
      musicScoreUrl: res?.musicScoreUrl?.url,
      songUrl: res?.songUrl?.url,
    };
    fetchCreateMusic(values);
  } catch (e) {}
};

/**
 * 接口相关
 */
// 获取消耗的a豆数
const fetchGetPoint = async () => {
  try {
    const res = await api.Common.getPoint({ type: 0 });
    data.adou = res.data;
  } catch (error) {}
};
// 提交
const fetchCreateMusic = async (params: Music.Create.Body) => {
  try {
    await api.Music.create({ ...params });
    uni.showModal({
      title: '提示',
      content: '提交成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.navigateBack();
        }
      },
    });
  } catch (e) {}
};

onLoad(() => {
  fetchGetPoint();
});

onShow(() => {
  // 接收下一个页面带回来的参数
  uni.$once('userAgreement', function (data) {
    if (data?.agree) {
      checked.value = data?.agree;
    }
  });
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #eaf8f4;
  padding-bottom: 60rpx;
  .form {
    margin: 0;
    padding: 0 24rpx;
  }
  .form-group {
    margin-bottom: 32rpx;
  }
  .label {
    font-size: 28rpx;
    color: #222;
    margin-bottom: 12rpx;
    font-weight: 500;
    display: flex;
    align-items: center;
  }
  .required {
    color: #ff4d4f;
    margin-left: 4rpx;
    font-size: 24rpx;
  }
  .input {
    width: 100%;
    height: 80rpx;
    background: #fff;
    border-radius: 16rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    border: none;
    margin-top: 8rpx;
  }
  .textarea {
    width: 100%;
    min-height: 120rpx;
    background: #fff;
    border-radius: 16rpx;
    padding: 16rpx 24rpx;
    font-size: 28rpx;
    border: none;
    margin-top: 8rpx;
  }
  .upload-box {
    width: 100%;
    height: 160rpx;
    background: #fff;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 8rpx;
    font-size: 60rpx;
    color: #bfbfbf;
    border: 2rpx dashed #d9d9d9;
  }
  .plus {
    font-size: 60rpx;
    color: #bfbfbf;
  }
  .disclaimer {
    display: flex;
    align-items: center;
    margin: 24rpx 0 0 0;
    font-size: 24rpx;
    color: #888;
  }
  .submit-btn {
    width: 100%;
    height: 90rpx;
    background: #1fa37a;
    color: #fff;
    font-size: 36rpx;
    border-radius: 60rpx;
    font-weight: 600;
    margin: 40rpx 0 0 0;
    border: none;
    box-shadow: 0 4rpx 16rpx 0 #e0e0e0;
  }
  .submit-btn:disabled {
    background: #b2d8c7;
    color: #fff;
  }
  .tip {
    text-align: center;
    color: #01604a;
    font-size: 26rpx;
    margin-top: 16rpx;
  }
  .form-item-label {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #606266;
    height: 80rpx;
  }
  .red-tip {
    color: #dd524d;;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .required-red {
    color: #dd524d;
    font-weight: bold;
  }
  :deep(.form-item-textarea textarea) {
    height: 150px;
  }
}

</style>
